package com.nulstudio.cloud.account.controller;

import com.nulstudio.cloud.account.domain.vo.LoginVo;
import com.nulstudio.cloud.account.request.RegisterRequest;
import com.nulstudio.cloud.account.request.UpdatePasswordRequest;
import com.nulstudio.cloud.account.service.AccountService;
import com.nulstudio.cloud.account.service.AuthorityService;
import com.nulstudio.cloud.account.service.PersonalInformationService;
import com.nulstudio.cloud.common.util.NulResult;
import jakarta.annotation.Resource;
import org.springframework.lang.NonNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Resource
    @NonNull
    private AccountService accountService;

    @Resource
    @NonNull
    private AuthorityService authorityService;

    @Resource
    @NonNull
    private PersonalInformationService personalInformationService;

    @GetMapping
    @NonNull
    public NulResult<LoginVo> login(@RequestParam @NonNull String userName, @RequestParam @NonNull String password) {
        return NulResult.response(accountService.login(userName, password));
    }

    @PostMapping
    @NonNull
    public NulResult<Void> register(@RequestBody @NonNull RegisterRequest request) {
        accountService.register(request.userName(), request.name(), request.password(),
                request.gender(), request.inviteCode());
        return NulResult.response();
    }

    @PutMapping("/password")
    @NonNull
    public NulResult<Void> updatePassword(@RequestBody @NonNull UpdatePasswordRequest updatePasswordRequest) {
        personalInformationService.updateCurrentPassword(updatePasswordRequest.password());
        return NulResult.response();
    }

    @PreAuthorize("hasAuthority('admin:read')")
    @GetMapping("/roles")
    public NulResult<List<String>> fetchRoles() {
        return NulResult.response(authorityService.getRoleNames());
    }
}
